<template>
  <div class="flex h-full">
    <div class="w-85 h-full p-4 flex-shrink-0 border-r flex flex-col border-gray-200 overflow-y-auto">
      <a-input class="mb-4" v-model:value.trim="state.searchName" placeholder="请输入搜索关键字" allow-clear @change="getFileTree">
        <template #suffix v-if="!state.searchName.length">
          <SearchOutlined style="color: #999" />
        </template>
      </a-input>
      <!-- 树状结构 -->
      <a-tree
        v-if="state.treeData.length > 0"
        v-model:selectedKeys="state.selectedKeys"
        class="tree-warpper"
        :block-node="true"
        :tree-data="state.treeData"
        show-icon
        default-expand-all
        @select="handleNodeSelect"
      >
        <template #title="{ name, data }">
          <div class="title-warpper">
            <span>{{ name }}</span>
            <span class="title-btn space-x-2 pr-2">
              <EditOutlined v-if="data.parentId" @click.stop="handleEdit(data)" />
              <a-popconfirm v-if="data.parentId" ok-text="确定" cancel-text="取消" @confirm="handleDelete(data)">
                <template #title>
                  <p>是否确认删除？</p>
                </template>
                <MinusCircleOutlined @click.stop="null" />
              </a-popconfirm>
              <PlusCircleOutlined @click.stop="handleAdd(data)" />
            </span>
          </div>
        </template>
      </a-tree>
    </div>
    <!-- 数据列表 -->
    <div class="px-4 :style={{ width: 'calc(100% - 340px)' }}">
      <DynamicForm class="mt-4" :config="config" :questions="questions" />
      <DynamicTable :tables="table" :config="tableConfig" ref="tableFormData">
        <!-- 文件类型详情 -->
        <template #fileName="{ text, record }">
          <span style="color: #005aea; cursor: pointer" @click="fileNameValue(record)">{{ text }}</span>
        </template>
        <!--状态-->
        <template #stateSwitch="{ record }">
          <a-switch :checked="record.status" checked-children="开" un-checked-children="关" :checked-value="1" :un-checked-value="0" @change="(value) => statusChange(record)" />
        </template>
      </DynamicTable>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, getCurrentInstance, createVNode, onBeforeUnmount } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { MinusCircleOutlined, PlusCircleOutlined, EditOutlined, MoreOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { DynamicForm, DynamicTable } from '@/components/public-template';
import { DYNAMICLAYERFORM, LOCALSUBSERVE, DYNAMICLAYERCLEAR } from '@/mixins/subject/subject-types';
import { CODE_RULE, generateCode } from '@/config/api/authorityManage';
import { fileGet, Api, fileAdd, fileTree, fileDelete, fileUpdateStatus } from '@/config/api/publicFile';
import Service from './index.service';
import { filter } from 'rxjs/operators';

const { proxy }: any = getCurrentInstance();
const tableFormData = ref();
const state = reactive({
  searchName: '',
  selectedKeys: [],
  treeData: [],
  selectParentId: ''
});
const config: any = {
  queryUrl: Api.filePage,
  labelCol: 4,
  wrapperCol: 20,
  grid: 8,
  style: 'table-form',
  cancelSave: true,
  combinationMethod(msg) {
    return Object.assign(msg, { parentId: state.selectParentId });
  }
};
const addConfig: any = {
  name: 'publicFileDist',
  type: 'layer',
  width: '424px',
  title: '添加文件类型',
  labelCol: 6,
  wrapperCol: 24,
  layout: 'vertical',
  localSub: true,
  data: {}
};
const tableConfig: any = {
  name: 'publicFileDist',
  queryUrl: Api.filePage,
  protType: 'post',
  isScreen: true
};
const questions: any = reactive(Service.getQuestions());
const table: any = reactive(Service.getTables());
const subscribeSub = proxy.$NotificationFormSub
  .getParams()
  .pipe(filter((res) => res !== 0))
  .subscribe((item: any) => {
    console.log('item', item);
    if (item.key === LOCALSUBSERVE && item.state.name == addConfig.name) {
      let params, fun;
      if (!item.value.id) {
        params = {
          code: item.value.code,
          name: item.value.name,
          parentId: item.value.parentId,
          codeRuleId: item.value.codeRuleId,
          versionRuleId: item.value.versionRuleId,
          watermarkingId: item.value.watermarkingId
        };
        fun = fileAdd;
      } else {
        params = {
          id: item.value.id,
          code: item.value.code,
          name: item.value.name,
          parentId: item.value.parentId,
          codeRuleId: item.value.codeRuleId,
          versionRuleId: item.value.versionRuleId,
          watermarkingId: item.value.watermarkingId
        };
        fun = fileAdd;
      }
      fun(params).then((res) => {
        if (res.success) {
          message.success(!item.value.id ? '添加成功' : '修改成功');
          getFileTree();
          proxy.$NotificationPubSub.pushParams({ key: DYNAMICLAYERCLEAR, value: { name: 'form' } });
          setTimeout(() => {
            tableFormData.value.getData();
          }, 1000);
        }
      });
    }
    if (item.key === LOCALSUBSERVE && item.state.name == detailConfig.name) {
      handleEdit(item.value);
    }
  });
getFileTree();

function getFileTree() {
  const params = {
    name: state.searchName
  };
  fileTree(params).then((res) => {
    if (res.success) {
      state.treeData = [
        {
          name: '全部',
          id: '0',
          children: res.data
        }
      ];
    }
  });
}
function handleNodeSelect(_: any, { node }) {
  console.log(node);
  const params = {
    parentId: node.id
  };
  state.selectParentId = node.id;
  tableFormData.value.getData(params);
}
// 添加文件类型
function handleAdd(record) {
  const showWater = !record.parentId;
  const addQuestions: any = reactive(Service.getAddQuestions('ADD', showWater));
  const params = { type: CODE_RULE.WJBM };
  addConfig.title = '添加文件类型';
  addConfig.okText = '确定';
  generateCode(params).then((res) => {
    if (res.success && res.data.length) {
      addConfig.data.code = res.data[0];
    }
    proxy.$NotificationPubSub.pushParams({
      key: DYNAMICLAYERFORM,
      value: {
        config: addConfig,
        form: addQuestions,
        data: {
          parentId: record.id
        }
      }
    });
  });
}
// 编辑文件类型
function handleEdit(record) {
  // 第一层可编辑水印
  const showWater = record.parentId == '0';
  const addQuestions: any = reactive(Service.getAddQuestions('EDIT', showWater));
  addConfig.title = '编辑文件类型';
  addConfig.okText = '确定';
  fileGet(record.id).then((res) => {
    if (res.success) {
      proxy.$NotificationPubSub.pushParams({
        key: DYNAMICLAYERFORM,
        value: {
          config: addConfig,
          form: addQuestions,
          data: {
            parentId: res.data.parentId,
            code: res.data.code,
            name: res.data.name,
            codeRuleId: res.data.codeRuleId,
            versionRuleId: res.data.versionRuleId,
            watermarkingId: res.data.watermarkingId,
            id: res.data.id
          }
        }
      });
    }
  });
}
// 查看文件类型详情
const detailConfig: any = {
  name: 'publicDetailDist',
  type: 'layer',
  width: '424px',
  title: '文件类型详情',
  okText: '编辑',
  cancelText: '返回',
  labelCol: 6,
  wrapperCol: 24,
  layout: 'vertical',
  localSub: true,
  data: {}
};
function ViewFileType(record) {
  const detailQuestions: any = reactive(Service.getViewQuestions());
  fileGet(record.id).then((res) => {
    if (res.success) {
      proxy.$NotificationPubSub.pushParams({
        key: DYNAMICLAYERFORM,
        value: {
          config: detailConfig,
          form: detailQuestions,
          data: {
            parentId: res.data.parentId,
            code: res.data.code,
            name: res.data.name,
            codeRuleId: res.data.codeRuleId,
            versionRuleId: res.data.versionRuleId,
            watermarkingName: res.data.watermarkingName,
            id: res.data.id
          }
        }
      });
    }
  });
}
// 删除文件类型
function handleDelete(record) {
  fileDelete(record.id).then((res) => {
    if (res.success) {
      message.success('删除成功');
      getFileTree();
      tableFormData.value.getData();
    }
  });
}
// 文件详情弹层
const fileNameValue = (record) => {
  ViewFileType(record);
};
// 状态更改事件
function statusChange(record) {
  Modal.confirm({
    title: '提示',
    icon: createVNode(ExclamationCircleOutlined),
    okText: '确定',
    cancelText: '取消',
    content: '是否确定修改状态',
    onOk() {
      fileUpdateStatus(record.id).then((res) => {
        if (res.success) {
          message.success('修改成功');
          tableFormData.value.getData({ parentId: state.selectParentId });
        }
      });
    }
  });
}

onBeforeUnmount(() => {
  subscribeSub && subscribeSub.unsubscribe();
  proxy.$NotificationPubSub.clearParams();
});
</script>

<style lang="less" scoped>
.title-warpper {
  .title-btn {
    float: right;
    display: none;
  }
  &:hover {
    .title-btn {
      display: inline-block;
    }
  }
}
:deep(.tree-warpper) {
  .ant-tree-switcher {
    line-height: 36px;
  }
  .ant-tree-node-content-wrapper {
    min-height: 36px;
    line-height: 36px;
    &.ant-tree-node-selected {
      background-color: #e5eefd;
      color: #005aea;
    }
  }
}
</style>
